package com.atguigu.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

public class Flink01_Batch_WordCount {
    public static void main(String[] args) throws Exception {
        /**
         * spark:
         * 1.创建SparkConf
         * 2.创建SparkContext
         * 3.读取文件->RDD（弹性式分布式数据集） readTextFile
         * 4.转换 -> 将一行数据转为 Tuple2元组 （word，1）flatMap
         * 5.reduceBykey -> 先将相同单词的数据聚合到一块 然后 累加
         * 6.行动算子 执行=》 提交job
         * 7.stop
         */

        //1.flink的执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        //2.读取文件中的数据
        DataSource<String> dataSource = env.readTextFile("input/word.txt");

        //3.将数据封装为Tuple2元组 （word，1）
        FlatMapOperator<String, Tuple2<String, Integer>> wordToOne = dataSource.flatMap(new MyFlatMap());

        //4.将相同的单词聚合到一块
        UnsortedGrouping<Tuple2<String, Integer>> groupBy = wordToOne.groupBy(0);

        //5.累加
        AggregateOperator<Tuple2<String, Integer>> result = groupBy.sum(1);

        result.print();
    }

    public static class MyFlatMap implements FlatMapFunction<String, Tuple2<String,Integer>>{

        /**
         *
         * @param value 传入Flatmap这个方法的数据 也就是要处理的数据
         * @param out 收集器 用来将数据发送至下游
         * @throws Exception
         */
        @Override
        public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
            //a.按照空格切分取出每一个单词
            String[] words = value.split(" ");
            //b.遍历数据取出每一个单词
            for (String word : words) {
                //c.将每一个单词组成Tuple2元组
//                out.collect(new Tuple2<>(word, 1));
                out.collect(Tuple2.of(word, 1));
            }
        }
    }
}
